package core.Resource
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import util.PathHelper;

	public class MapPackManager extends EventDispatcher
	{
		
		private var _packs:Array;
		
		public function MapPackManager()
		{
			_packs = [];
		}
		
		public static function get instance():MapPackManager
		{
			if(_instance == null)
				_instance = new MapPackManager();
			return _instance;
		}
		
		//block name 应该为0_0形式
		public function getBlockPack(sceneName:String,blockName:String):MapPack
		{
			var packName:String = sceneName+ getMapPackNameByBlockName(blockName);
			
			if(_packs[packName]!=null)
			{
				return _packs[packName];
			}
			else
			{
				return loadPack(packName);
			}
		}
		
		
		private function loadPack(name:String):MapPack
		{
			var p:MapPack = new MapPack();
			
			p.load(name,PathHelper.getMapTilePackPath(name));
			p.addEventListener(Event.COMPLETE,packCompleteHandler);
			_packs[p.name] = p;
			return p;
		}
		
		private function packCompleteHandler(e:Event):void
		{
			var pack:MapPack = e.target as MapPack;
			pack.removeEventListener(Event.COMPLETE,packCompleteHandler);
			this.dispatchEvent(new MapPackEvent(MapPackEvent.COMPLETE,pack));
		}
		
		
		private function getMapPackNameByBlockName(blockName:String):String
		{
			//每个包打包2*2四块地图
			var splitedBlockName:Array = blockName.split("_");
			var x:int = int(splitedBlockName[0]);
			var y:int = int(splitedBlockName[1]);
			var resultX:int = int(x/2)*2;
			var resultY:int = int(y/2)*2;
			return resultX+"_"+resultY; 
		}
		
		
		
		
		private static var _instance:MapPackManager;
	}
}